﻿using System;
using System.Xml;

namespace BuzzX8.Xmpp.StreamElements
{
    public class StreamHeader : DatagramElement
    {
        private StreamType streamType;

        public StreamHeader(StreamType streamType) : this(streamType, null)
        {
        }

        public StreamHeader(StreamType streamType, object id) : this(streamType, null, null, id)
        {}

        public StreamHeader(StreamType streamType, JID from, JID to) : this(streamType, from, to, null)
        {}

        public StreamHeader(StreamType streamType, JID from, JID to, object id) : base("stream", "stream", XmppNamespaces.Streams)
        {
            this.streamType = streamType;
            ContentNamespace = GetNamespaceForType(streamType);
            Version = "1.0";
            From = from;
            To = to;
            Id = id;
        }

        public string Version
        {
            get { return (string) Attributes["version"]; }
            set { Attributes["version"] = value; }
        }

        public StreamType StreamType
        {
            get
            {
                return GetStreamTypeForNamespace(ContentNamespace.Uri);
            }
            set
            {
                ContentNamespace = GetNamespaceForType(value);
            }
        }

        private StreamType GetStreamTypeForNamespace(string namespceUri)
        {
            if (namespceUri == XmppNamespaces.JabberClient)return StreamType.Client;
            if (namespceUri == XmppNamespaces.JabberServer)return StreamType.Server;
            return StreamType.None;
        }

        public bool WriteXmlDeclaration { get; set; }

        private string GetNamespaceForType(StreamType type)
        {
            switch (type)
            {
                case StreamType.Client:
                    return XmppNamespaces.JabberClient;

                case StreamType.Server:
                    return XmppNamespaces.JabberServer;

                default:
                    throw new NotImplementedException();
            }
        }

        protected override void WriteStartElement(XmlWriter writer)
        {
            if (WriteXmlDeclaration) writer.WriteRaw("<?xml version='1.0'?>");
            base.WriteStartElement(writer);
        }

        protected override void WriteEndElement(XmlWriter writer)
        { }
    }
}
